package cz.muni.fi.pb168.eis_web;

import cz.muni.fi.pb138.eis_core.ArtworkEntity;
import cz.muni.fi.pb138.eis_core.ArtworkManager;
import cz.muni.fi.pb138.eis_core.ArtworkManagerImpl;
import cz.muni.fi.pb138.eis_core.DBTools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.xquery.XQException;

/**
 *
 * @author Jakub Senko
 */
@WebServlet(urlPatterns =
{
    "/"
})
public class IndexServlet extends HttpServlet
{

    // SimpleAuthenticator is thread safe
    Authenticator authenticator = new SimpleAuthenticator();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, XQException
    {
        ServletContext sc = getServletContext();

        String path = request.getRequestURI();//.substring(request.getContextPath().length()+1, request.getRequestURI().length());

        if(path.matches("^" + request.getContextPath() + "/public.*"))
        {
            String filename = sc.getRealPath(path.replaceFirst(request.getContextPath() + "/", ""));
            //path.replaceFirst(request.getContextPath() + "/", "");
            // Get the MIME type of the image
            String mimeType = sc.getMimeType(filename);
            if(mimeType == null)
            {
                sc.log("Could not get MIME type of " + filename);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
            // Set content type
            response.setContentType(mimeType);

            // Set content size
            File file = new File(filename);
            response.setContentLength((int) file.length());

            // Open the file and output streams
            FileInputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();

            // Copy the contents of the file to the output stream
            byte[] buf = new byte[1024];
            int count = 0;
            while((count = in.read(buf)) >= 0)
            {
                out.write(buf, 0, count);
            }
            in.close();
            out.close();
            return;
        }
        
        UserLogin userLogin = new UserLogin(request.getSession(true), authenticator);

        if("login".equals(request.getParameter("action")))
        {
            actionLogin(userLogin, request, response);
        }

        if("logout".equals(request.getParameter("action")))
        {
            actionLogout(userLogin, request, response);
        }

        if(userLogin.isLoggedIn())
        {
            list(request);
            request.setAttribute("isLoggedIn", true);
            forward("/backend/index.jsp", request, response);
        }
        else
        {
            

            forward("/frontend/index.jsp", request, response);
        }
    }

    void actionLogin(UserLogin userLogin, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, XQException
    {
        if(userLogin.login(request.getParameter("userName"), request.getParameter("password")))
        {
            list(request);
            request.setAttribute("isLoggedIn", true);
            forward("/backend/index.jsp", request, response);
        }
        else
        {
            request.setAttribute("loginFail", true);
            forward("/frontend/index.jsp", request, response);
        }
    }

    void actionLogout(UserLogin userLogin, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        userLogin.logout();
        forward("/frontend/index.jsp", request, response);
    }

    void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.getRequestDispatcher(path).forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        try
        {
            processRequest(request, response);
        }
        catch(XQException ex)
        {
            Logger.getLogger(IndexServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        try
        {
            processRequest(request, response);
        }
        catch(XQException ex)
        {
            Logger.getLogger(IndexServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "TODO.";
    }// </editor-fold>

    private void list(HttpServletRequest request) throws XQException
    {
            
            List<ArtworkEntity> all = ((ArtworkManager)getServletContext().getAttribute("artworkManager")).getAll();
            request.setAttribute("artworks", all);
    }
}
